<?php

namespace App\Http\Controllers\Admin;

use App\Models\Advert;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class AdvertController extends Controller
{

    public function index(Request $request)
    {
        $limit = $request->get('limit', 10);
        $keys = $request->get('keys');
        $model = Advert::query();
        if ($keys) {
            $model = $model->where('title', 'like', '%' . $keys . '%');
        }
        $result = $model->orderBy('sort', 'asc')->orderBy('id', 'desc')->paginate($limit);
        foreach ($result as $value) {
            if ($value['thumb']) {
                $value['thumb'] = getAliOssImage($value['thumb']);
            }
        }
        return showMsg('操作成功', 200, $result);
    }


    public function detail(Request $request)
    {
        $id = $request->get('id');
        $result = Advert::findOrFail($id);
        if (!$result) {
            return showMsg('信息已删除', 201, $result);
        }
        if ($result['urls_type'] == 1) {
            $urls = explode('?', $result['urls']);
            $ids = explode('=', $result['urls']);
            $result['urls'] = $urls[0];
            $result['ids'] = $ids[1];
        }
        if ($result['thumb']) {
            $result['thumb'] = getAliOssImage($result['thumb']);
        }
        return showMsg('操作成功', 200, $result);
    }


    public function beforeSave(Request $request)
    {
        $id = $request->get('id');
        $data = $request->all();
        if ($data['urls_type'] == 1) {
            $data['urls'] = $data['urls'] . "?id=" . $data['ids'];
        }
        if ($data['thumb']) {
            $data['thumb'] = delAliOssImage($data['thumb']);
        }
        if ($id) {
            $article = Advert::findOrFail($id);
            if ($article->update($data)) {
                return showMsg('更新成功', 200);
            }
        } else {
            Advert::create($data);
            return showMsg('添加成功', 200);
        }
    }


    public function destroy(Request $request)
    {
        $ids = $request->get('ids');
        if (empty($ids)) {
            return showMsg('请选择操作项', 201);
        }
        if (is_array($ids)) {
            foreach ($ids as $v) {
                Advert::destroy('id', $v);
            }
        } else {
            Advert::destroy('id', $ids);
        }
        return showMsg('删除成功', 200);
    }

    public function setStatus(Request $request)
    {
        $id = $request->get('id');
        $re = Advert::where('id', $id)->first();
        if ($re['status'] == 1) {
            Advert::where('id', $id)->update(['status' => 0]);
        } else {
            Advert::where('id', $id)->update(['status' => 1]);
        }
        return showMsg('设置成功', 200);
    }

}
